<?php

declare(strict_types=1);

namespace App\Command;

use App\Helpers\RedisUtil;
use App\Model\UserMsgLog;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
class TableSplittingCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('tableSplitting:user_msg_log');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('消息表拆分');
    }

    public function handle()
    {
        $this->splitting();
    }

    public function splitting()
    {
        $lastId = (int)RedisUtil::get('tableSplitting:user_msg_log:lastId');
//        $lastId = 2947056;

        $this->line('开始ID: '.$lastId, 'info');

        for ($i = 0; $i < 1000; $i++) {
            $msgLog = UserMsgLog::limit(1000)
                ->where('id', '>', $lastId)
                ->where('id', '<', $lastId + 1000)
                ->where('created_at', '<', '2022-10-01')->get()->toArray();

            if (empty($msgLog)) {
                $this->line('数据已跑完', 'info');

                break;
            }

            $text = "2209 插入".count($msgLog).'条';
            $this->line($text, 'info');
            Db::table('user_msg_log_202209')->insert($msgLog);

            $text = "lastId: ".$lastId;
            $this->line($text, 'info');

            RedisUtil::set('tableSplitting:user_msg_log:lastId', $lastId);
        }
    }
}
